import { useReducer } from "react";
import Mock from "mockjs";
interface Goods {
  id: number;
  name: string;
  price: number;
  count: number;
}
type ActionName = "add" | "sub" | "delete" | "clear" | "edit";
export default function Demo02() {
  const [goods, dispatch] = useReducer(shopCartReducer, [], () => {
    return Mock.mock({
      "list|10": [
        {
          "id|+1": 1,
          name: "@cword(3, 5)",
          "price|10-100.2": 1,
          "count|1-10": 1,
        },
      ],
    }).list as Goods[];
  });
  return (
    <>
      <h1>useReducer示例</h1>
      <table width={800} border={1} cellPadding={5} cellSpacing={0}>
        <thead>
          <tr>
            <th>商品名称</th>
            <th>价格</th>
            <th>数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {goods.map((item) => (
            <tr key={item.id}>
              <td align="center">{item.name}</td>
              <td align="center">{item.price.toFixed(2)}</td>
              <td align="center">
                <button onClick={() => dispatch({ type: "add", id: item.id })}>+</button>
                {item.count}
                <button onClick={() => dispatch({ type: "sub", id: item.id })}>-</button>
              </td>
              <td align="center">
                <button onClick={() => dispatch({ type: "edit", id: item.id })}>编辑</button>
                <button onClick={() => dispatch({ type: "delete", id: item.id })}>删除</button>
              </td>
            </tr>
          ))}
        </tbody>
        <tfoot>
          <tr>
            <td colSpan={4}>
              <span style={{lineHeight: '2.5'}}>总价：{goods.reduce((total, item) => total + item.price * item.count, 0).toFixed(2)}</span>
              <button style={{float: 'right'}} onClick={() => dispatch({ type: "clear", id: -1 })}>清空购物车</button>
            </td>
          </tr>
        </tfoot>
      </table>
    </>
  );
}

function shopCartReducer(state: Goods[], { type, id }: { type: ActionName; id: number }) {
  switch (type) {
    case "add":
      return state.map((item) => {
        if (item.id === id) {
          return { ...item, count: item.count + 1 };
        }
        return item;
      });
    case "sub":
      return state.map((item) => {
        if (item.id === id) {
          return { ...item, count: item.count - 1 };
        }
        return item;
      });
    case "delete":
      return state.filter((item: Goods) => item.id !== id);
    case "clear":
      return [];
    case "edit":
      return state.map((item) => {
        if (item.id === id) {
          // 这里可以添加编辑逻辑，比如弹出一个输入框让用户修改商品信息
          const newName = prompt("请输入新的商品名称", item.name);
          if (newName) {
            return { ...item, name: newName };
          }
        }
        return item;
      })
    default:
      return state;
  }
}
